package com.wsj.beanFactory;

import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionVisitor;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.StringValueResolver;

// ObscenityRemovingBeanFactoryProcessor.java文件
public class ObscenityRemovingBeanFactoryProcessor implements BeanFactoryPostProcessor {

  private Set<String> obscenities;

  public ObscenityRemovingBeanFactoryProcessor() {
    this.obscenities = new HashSet<String>();
  }

  @Override
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    String[] beanNames = beanFactory.getBeanDefinitionNames();
    for (String beanName : beanNames) {
      BeanDefinition bd = beanFactory.getBeanDefinition(beanName);
      StringValueResolver valueResolver = new StringValueResolver() {
        @Override
        public String resolveStringValue(String strVal) {
          if (isObscene(strVal)) {
            return "******";
          }
          return strVal;
        }
      };

      BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(valueResolver);
      visitor.visitBeanDefinition(bd);
    }
  }

  private boolean isObscene(Object value) {
    String potentialObscene = value.toString().toUpperCase();
    return this.obscenities.contains(potentialObscene);
  }

  public void setObscenities(Set<String> obscenities) {
    this.obscenities.clear();
    this.obscenities.addAll(obscenities);
  }
}